# -*- encoding: utf-8 -*-
from odoo import models, fields, api

from odoo.exceptions import UserError


class summary_generate_voucher(models.TransientModel):
    _name = 'summary.generate.voucher'
    _description = u'发票汇总凭证开立'

    period_id = fields.Many2one('account.period', u'期别', domain="[('gl_state','=','open')]")
    start_date = fields.Date(u'起始日', required=True, )
    end_date = fields.Date(u'截止日', required=True, )
    invoice_type = fields.Selection([('sale', u'销售'),
                                     ('purchase', u'采购')], u'发票类型', required=True, default='sale')
    is_rework = fields.Boolean(u'预切重做', default=False)

    @api.onchange('period_id')
    def onchange_period_id(self):
        if self.period_id:
            self.start_date = self.period_id.date_start
            self.end_date = self.period_id.date_stop

    def action_confirm(self):
        self.ensure_one()
        domain = [('date', '>=', self.start_date),
                  ('date', '<=', self.end_date),
                  ('is_summary_generate_voucher', '=', True),
                  ('state', 'in', ('open', 'paid'))]
        if self.invoice_type == 'sale':
            domain.extend([('type', 'in', ('out_invoice', 'out_refund'))])
            origin = u'销售发票汇切凭证'
        if self.invoice_type == 'purchase':
            domain.extend([('type', 'in', ('in_invoice', 'in_refund'))])
            origin = u'采购发票汇切凭证'
        invoices = self.env['cncw.invoice.move'].search(domain)

        if self.is_rework:
            for x in invoices:
                # x.action_test()
                x.generate_cancel_voucher_script()
                x.generate_account_voucher_script()

        if invoices:

            sql = """
                select a.account_id,a.sub_account_id,a.name,
                       sum(coalesce(credit,0)*(case when a.dc_type='D' then 1.0 else -1.0 end)+coalesce(debit,0)*(case when a.dc_type='D' then 1.0 else -1.0 end)) as amount,
                       sum(coalesce(lc_credit,0)*(case when a.dc_type='D' then 1.0 else -1.0 end)+coalesce(lc_debit,0)*(case when a.dc_type='D' then 1.0 else -1.0 end)) as lc_amount
                 from account_voucher_script_line a left join cncw_account b on a.account_id=b.id
                where a.invoice_id in %s
                group by a.account_id,a.sub_account_id,a.name
                order by a.sub_account_id desc,a.account_id ;
            """
            self._cr.execute(sql, (tuple(invoices.ids),))
            res = self._cr.fetchall()
            items = []
            for account_id, sub_account_id, name, amount, lc_amount in res:
                if amount > 0:
                    credit = 0.0
                    debit = amount
                    dc_type = 'D'
                elif amount < 0:
                    credit = -amount
                    debit = 0.0
                    dc_type = 'C'
                else:
                    continue
                item = dict(account_id=account_id,
                            sub_account_id=sub_account_id,
                            dc_type=dc_type,
                            name=name,
                            credit=credit,
                            debit=debit,
                            lc_credit=credit,
                            lc_debit=debit, )
                items.append((0, 0, item))
            if items:
                voucher_ids = invoices.mapped('voucher_id')
                if len(voucher_ids) > 1:
                    raise UserError(u"所选区间不可有两张凭自动生成汇切凭证:{voucher_ids}".format(voucher_ids=','.join(voucher_ids)))
                if len(voucher_ids) == 1:
                    self._cr.execute("""delete from account_voucher_line where master_id={master_id}""".format(
                        master_id=voucher_ids[0].id))
                    voucher_id = voucher_ids[0]
                    voucher_id.origin = origin
                else:
                    vals = dict(voucher_category_id=self.env.ref('cncw_ledger.account_voucher_category_09').id,
                                date=self.end_date,
                                period_id=self.period_id.id,
                                origin=origin,
                                note=';'.join(invoices.mapped('invoice_no')) or '')
                    voucher_id = self.env['account.voucher'].create(vals)
                voucher_id.write(dict(line_ids=items))
                invoices.write(dict(voucher_id=voucher_id.id))
        return {
            'name': '记账凭证',
            'type': 'ir.actions.act_window',
            'view_mode': 'tree',
            'res_model': 'account.voucher',
        }
